/**
 * @description 委外投资 持仓
 * @author LT
 */
import React, { PureComponent } from 'react';
import { connect } from 'dva';
import { TableC, ExportC } from '../../../../comps';
import { QuestionCircleOutlined } from '@ant-design/icons';
import { Tooltip } from 'antd';
import SetColumns from '../common/SetColumns';
import accounting from 'accounting';
import _ from 'lodash';
import config from '../../../../comps/business/tradingMarket/config';
import moment from 'moment';
import { CollectC } from '../../../../comps';

@connect(({ positionInquiryM, globalM, loading }) => ({
  globalM,
  positionInquiryM,
  loading,
}))
export default class StockFuture extends PureComponent {
  constructor(props) {
    super(props);
    this.scrollx = 0;
    this.newColumns = [];
    this.state = {
      search: {},
      columns: [],
      dataSource: [],
      page: 1,
      pageSize: 20,
      total: 0,
      account: {},
      treeData: [],
      checkedKeys: [],
      scrollx: 0,
    };
  }
  componentDidMount() {
    const { dispatch, stockFutureArgs } = this.props;
    // 查表头信息
    dispatch({
      type: 'positionInquiryM/queryShowCol',
      payload: {
        type: 'Trade_Ana_Futures_Hold_Info',
      },
      callback: (data) => {},
    });
    this.setState(
      {
        search: stockFutureArgs,
      },
      () => {
        this.getTableData();
      },
    );
  }
  UNSAFE_componentWillReceiveProps(nextProps) {
    const init = !this.props.stockFutureArgs ? '' : JSON.stringify(this.props.stockFutureArgs);
    const initN = !nextProps.stockFutureArgs ? '' : JSON.stringify(nextProps.stockFutureArgs);
    if (init != initN) {
      this.setState(
        {
          search: nextProps.stockFutureArgs,
        },
        () => {
          this.getTableData();
        },
      );
    }
  }
  //分页切换
  handleTableChange = (pagination, filter, sorter) => {
    const { current, pageSize } = pagination;
    this.setState(
      {
        page: current,
        pageSize: pageSize,
      },
      () => {
        this.getTableData('pageChange');
      },
    );
  };

  //查询表格数据
  getTableData = (type) => {
    const { dispatch } = this.props;
    const { page, pageSize, search } = this.state;
    const params = {};
    params.pageSize = pageSize;
    if (type != 'pageChange') {
      //点击查询按钮 重置页码
      this.setState({
        page: 1,
      });
      params.page = 1;
    } else {
      //点击页码切换时候调用
      params.page = page;
    }

    //列表数据
    dispatch({
      type: 'positionInquiryM/stockFutureTable',
      payload: {
        ...params,
        ...search,
      },
      callback: (res) => {
        res.data &&
          res.data.map((item, key) => {
            item.key = key;
          });
        this.setState({
          dataSource: res.data,
          total: res.total,
        });
      },
    });

    if (type != 'pageChange') {
      //获取统计信息
      dispatch({
        type: 'positionInquiryM/getSearchTotal',
        payload: {
          ...search,
          type: '23',
        },
        callback: (data) => {
          this.setState({
            account: data,
          });
        },
      });
    }
  };

  // 导出参数调整
  changeSearch() {
    const { search } = this.state;
    let newSearch = _.cloneDeep(search);
    if (newSearch && newSearch.fundId) {
      newSearch.fundId = newSearch.fundId.join(',');
    }
    return newSearch;
  }

  render() {
    const {
      positionInquiryM: { columnsInfo, checkedKeysInfo },
      loading,
      globalM: { dataDictionary },
    } = this.props;
    const { search, account = {} } = this.state;
    const columns = _.cloneDeep(columnsInfo[15].columns);
    this.newColumns = columns.filter((item) => item.display == true);
    if (this.newColumns && this.newColumns.length > 10) {
      const a = this.newColumns.length;
      this.scrollx = a * 150;
    } else {
      this.scrollx = 0;
    }

    this.newColumns.map((item) => {
      if (['id.dataDt'].includes(item.key)) {
        item.type = 'date';
      }
      if (item.key == 'id.dataDt') {
        item.render = (_, record) => {
          const text = record?.id?.dataDt;
          if (text != '--' && text) {
            return text.slice(0, 4) + '-' + text.slice(4, 6) + '-' + text.slice(6);
          } else {
            return '--';
          }
        };
      }
      if (item.key == 'id.tradingcode') {
        item.render = (_, record) => {
          const text = record?.id?.tradingcode;
          if (text != '--' && text) {
            return text;
          } else {
            return '--';
          }
        };
      }
      if (item.key == 'lCurrentAmount') {
        item.type = 'number';
      }
      if (item.key == 'contractMultiplie') {
        item.width = '100px';
      }
      if (['contractMultiplie', 'marketValue', 'enFloatProfit', 'currentPrice'].includes(item.key)) {
        item.type = 'money';
      }
      if (item.key == 'investmentType') {
        item.title = (
          <span>
            投资类型
            <Tooltip title='展示的投资类型为同组合同标的的最近一次修改持仓操作'>
              <QuestionCircleOutlined style={{ paddingLeft: '7px' }} />
            </Tooltip>
          </span>
        );
      }
      if (item.key == 'futureFlag') {
        //交易属性
        item.render = (text, record) => {
          return dataDictionary?.MAAT_FUT_STOCKTYPE?.find((item) => item.code == record.id?.futureFlag)?.value || '--';
        };
      }
      if (item.key == 'posType') {
        //持仓类型
        item.render = (text, record) => {
          return dataDictionary?.POSITION_TYPE?.find((item) => item.code == text)?.value || '--';
        };
      }
      if (item.key == 'investType') {
        //投资种类
        item.render = (text, record) => {
          return dataDictionary?.TZTYPE?.find((item) => item.code == text)?.value || '--';
        };
      }
      if (item.key == 'costPrice' || item.key == 'cost') {
        //成本价、成本
        item.align = 'right';
        item.render = (text) => {
          return text !== null && text !== undefined ? accounting.formatNumber(text * 1, 2) : '';
        };
      }
      if (item.key == 'jysc') {
        item.render = (text, record) => {
          if (record?.id?.exchangecode) {
            let findvalue = config.filter((item) => {
              return item.value == record.id.exchangecode;
            });
            if (findvalue && findvalue.length > 0) {
              return findvalue[0].title;
            } else {
              return '--';
            }
          } else {
            return '--';
          }
        };
      }
    });

    return (
      <div>
        <div style={{ display: 'flex', marginBottom: '10px', alignItems: 'center' }}>
          <div style={{ flex: 1, marginRight: '16px' }}>
            <CollectC
              dataSource={[
                {
                  name: '买入开仓数量', //名称
                  value: account.buyNum, //数值
                },
                {
                  name: '卖出开仓数量', //名称
                  value: account.saleNum, //数值
                },
                {
                  name: '市值', //名称
                  value: account.marketValue, //数值
                  toFixed: 4,
                },
                {
                  name: '浮动盈亏', //名称
                  value: account.enFloatProfit, //数值
                  toFixed: 4,
                },
              ]}
              isloading={loading.effects['positionInquiryM/getSearchTotal']}
              type='1'
            />
          </div>
          <div style={{ display: 'flex' }}>
            <div>
              <ExportC style={{ marginTop: '10px' }} url='api/v1/tradeAnaFutureHoldInfo/export' search={this.changeSearch()} />
            </div>
            <div style={{ marginLeft: '5px', marginTop: '10px' }}>
              <SetColumns type='15' parameter='Trade_Ana_Futures_Hold_Info' checkedKeysInfo={checkedKeysInfo} />
            </div>
          </div>
        </div>
        <TableC
          columns={this.newColumns || []}
          dataSource={this.state.dataSource || []}
          onChange={this.handleTableChange}
          current={this.state.page}
          pageSize={this.state.pageSize}
          total={this.state.total}
          selfScrollY={true}
          scroll={{ x: this.scrollx }}
          loading={loading.effects['positionInquiryM/stockFutureTable']}
          rowKey={'key'}
        />
      </div>
    );
  }
}
